/**
 * Copyright (c) 2011-2016, James Zhan 詹波 (jfinal@126.dao).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.springboot.cms.kit;

import java.io.*;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;

/**
 * FileKit.
 */
public class FileKit {
	public static void delete(File file) {
		if (file != null && file.exists()) {
			if (file.isFile()) {
				file.delete();
			}
			else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i=0; i<files.length; i++) {
					delete(files[i]);
				}
			}
			file.delete();
		}
	}

	/**
	 * 删除文件或文件夹
	 * @param path
	 *            待删除的文件的绝对路径
	 * @return boolean
	 */
	public static boolean deleteFile(String path) {
		boolean flag = false;

		File file = new File(path);
		if (!file.exists()) { // 文件不存在直接返回
			return flag;
		}

		flag = file.delete();

		return flag;
	}
	public static File mkDirs(String path) {
		return mkDirs(new File(path));
	}

	public static File mkDirs(File file) {
		if (file == null) {
			try {
				throw new FileNotFoundException("File could not be null. - " + file);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		File parent = file.getParentFile();
		if (!parent.exists()) {
			if (!parent.mkdirs()) {
				try {
					throw new Exception("Directory " + parent.getAbsolutePath() + " not exists and can not create directory.");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return file;
	}

	public static boolean exist(String file) {
		Enumeration<URL> urls = null;
		try {
			urls = Thread.currentThread().getContextClassLoader().getResources(file);
			while (urls.hasMoreElements()) {
				return true;
			}
		} catch (IOException e) {
			try {
				throw new FileNotFoundException("Could not getResource from file - " + file);
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			}
		}
		return false;
	}

	/**
	 * 文件重命名
	 * @param path 文件路径 比如：var/user/img/icon
	 * @param oldname 源文件名称  比如：head.jsp
	 * @param newname 命名后的文件名称  比如：head-icon.jsp
	 */
	public static void renameFile(String path,String oldname,String newname){
		if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名
			File oldfile=new File(path+ File.separator+oldname);
			File newfile=new File(path+ File.separator+newname);
			if(!oldfile.exists()){
				System.out.println("文件不存在");
				return;//重命名文件不存在
			}
			if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同，则不允许重命名
				System.out.println(newname+"已经存在！");
			else{
				oldfile.renameTo(newfile);
			}
		}else{
			System.out.println("新文件名和旧文件名相同...");
		}
	}


	/**
	 * 复制文件到目标目录
	 * @param srcPath
	 *            源文件绝对路径
	 * @param destDir
	 *            目标文件所在目录
	 * @param overwriteExistFile
	 *            是否覆盖目标目录下的同名文件
	 * @return boolean
	 */
	public static boolean copyFile(String srcPath, String destDir, boolean overwriteExistFile) throws IOException {
		boolean flag = false;

		File srcFile = new File(srcPath);
		if (!srcFile.exists() || !srcFile.isFile()) { // 源文件不存在
			return false;
		}

		//获取待复制文件的文件名
		String fileName = srcFile.getName();
		String destPath = destDir + File.separator +fileName;
		File destFile = new File(destPath);
		if (destFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) { // 源文件路径和目标文件路径重复
			return false;
		}
		if(destFile.exists() && !overwriteExistFile) {    // 目标目录下已有同名文件且不允许覆盖
			return false;
		}

		File destFileDir = new File(destDir);
		if(!destFileDir.exists() && !destFileDir.mkdirs()) {    // 目录不存在并且创建目录失败直接返回
			return false;
		}

			FileInputStream fis = new FileInputStream(srcPath);
			FileOutputStream fos = new FileOutputStream(destFile);
			byte[] buf = new byte[1024];
			int c;
			while ((c = fis.read(buf)) != -1) {
				fos.write(buf, 0, c);
			}
			fos.flush();
			fis.close();
			fos.close();

			flag = true;


		return flag;
	}

	/**
	 * 输出文件到流
	 *
	 * @param srcPath
	 *            源文件绝对路径
	 * @param os
	 *            输出流
	 */
	public static boolean copyFile(String srcPath, OutputStream os) {
		boolean flag = false;
		File srcFile = new File(srcPath);
		if (!srcFile.exists() || !srcFile.isFile()) { // 源文件不存在
			return false;
		}
		try {
			FileInputStream is = new FileInputStream(srcFile);
			int b = 0;
			byte[] buffer = new byte[1024];
			while ((b = is.read(buffer)) != -1) {
				os.write(buffer, 0, b);
			}
			is.close();
			os.flush();
			os.close();
			flag = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}




	/**
	 * 获取inputFilePath的后缀名，如："e:/test.pptx"的后缀名为："pptx"<br>
	 *
	 * @param inputFilePath
	 * @return
	 */
	public static String getPostfix(String inputFilePath) {
		return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
	}


	public static List<File> listFiles(String path,List<File> fileList){
		File file=new File(path);
		if (file.exists()){
			File[] files = file.listFiles();
			if (files==null || files.length == 0) {
//				System.out.println(file+"文件夹是空的!");
				return null;
			} else {
				for (File file2 : files) {
					if (file2.isDirectory()) {
//						System.out.println("文件夹:" + file2.getAbsolutePath());
						listFiles(file2.getAbsolutePath(),fileList);
					} else {
						System.out.println("文件:" + file2.getAbsolutePath());
						fileList.add(file2);
					}
				}
			}

		}else {
			System.out.println(path+"---->不存在");
		}
//		System.out.println(fileList.size()+" 个文件");
		return fileList;
	}
}
